package com.yanqu.road.server.cmd.activity.huashigang;

import com.yanqu.road.entity.activity.ActivityInfo;
import com.yanqu.road.pb.huashigang.HuaShiGangProto;
import com.yanqu.road.server.cmd.base.AbstractCommand;
import com.yanqu.road.server.command.Cmd;
import com.yanqu.road.server.gameplayer.GamePlayer;
import com.yanqu.road.server.gameplayer.module.player.CurrencyModule;
import com.yanqu.road.server.manger.activity.ActivityMgr;
import com.yanqu.road.server.manger.activity.huashigang.HuaShiGangMgr;
import com.yanqu.road.message.YanQuMessage;
import com.yanqu.road.server.protocol.ClientProtocol;
import com.yanqu.road.server.protocol.CrossProtocol;
import com.yanqu.road.server.protocol.GameErrorCode;
import com.yanqu.road.server.protocol.GameProtocol;
import com.yanqu.road.utils.property.Property;

import java.math.BigInteger;

/**
 * @Author wpj
 * @Date 2020/10/6
 */
@Cmd(code = GameProtocol.S_HUA_SHI_GANG_OPEN_BOX, desc = "花石纲打开宝箱")
public class OpenBoxCmd extends AbstractCommand {

    int boxId;
    int num = 1;

    @Override
    public boolean parseData(YanQuMessage packet) throws Exception {
        HuaShiGangProto.OpenBoxReqMsg msg = HuaShiGangProto.OpenBoxReqMsg.parseFrom(packet.getBytes());
        boxId = msg.getBoxId();
        if (msg.hasNum()) {
            num = msg.getNum();
        }
        return true;
    }

    @Override
    public void execute(GamePlayer player, YanQuMessage packet) throws Exception {
        ret = HuaShiGangMgr.getActivityInfoRet(player);
        if (ret != 0) {
            return;
        }
        ActivityInfo activityInfo = HuaShiGangMgr.getActivityInfo();
        if (!ActivityMgr.activityInShowTime(activityInfo)) {
            ret = GameErrorCode.E_ACTIVITY_OVER_TIME;
            return;
        }

        if (num < 0 || num > 99999) {
            ret = GameErrorCode.E_HUA_SHI_GANG_COST_ERROR;
            return;
        }

        Property property = new Property();
        property.addProperty(HuaShiGangMgr.getHuaShiGangActivityEventConfigMap().get(boxId).getOpenCostKeyId(), BigInteger.valueOf(num));
        if (!player.getModule(CurrencyModule.class).currencyIsEnough(property)) {
            ret = GameErrorCode.E_BAG_ITEM_NO_ENOUGH;
            return;
        }

        HuaShiGangMgr.preReduceKey(player, boxId, num);
        HuaShiGangProto.CrossOpenBoxReqMsg.Builder builder = HuaShiGangProto.CrossOpenBoxReqMsg.newBuilder();
        builder.setActivityId(activityInfo.getActivityId());
        builder.setBoxId(boxId);
        builder.setNum(num);
        player.sendPacket(CrossProtocol.C2_HUA_SHI_GANG_OPEN_BOX, builder);
    }

    @Override
    public void sendData(GamePlayer player) {
        if (ret != 0) {
            HuaShiGangProto.OpenBoxRespMsg.Builder builder = HuaShiGangProto.OpenBoxRespMsg.newBuilder();
            builder.setRet(ret);
            player.sendPacket(ClientProtocol.U_HUA_SHI_GANG_OPEN_BOX, builder);
        }
    }
}
